package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class SearchController {

    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String, String> searchMap) {
        //如果没有currentPage,为了防止空指针,设置默认值为1
        if (searchMap.get("currentPage") == null) {
            searchMap.put("currentPage", "1");
        }
        int currentPageInt = Integer.parseInt(searchMap.get("currentPage"));
        model.addAttribute("currentPageInt", currentPageInt); //把Integer形式的currentPage返回前台

        //排序
        if (searchMap.get("sort") == null) {
            searchMap.put("sort", "");
        }
        if (searchMap.get("sortOrder") == null) {
            searchMap.put("sortOrder", "DESC");
        }

        Map result = skuSearchService.search(searchMap);
        model.addAttribute("result", result);

        //url处理
        StringBuilder url = new StringBuilder("/search.do?");
        for (String key : searchMap.keySet()) {
            url.append("&" + key + "=" + searchMap.get(key));
        }
        model.addAttribute("url", url.toString());
        model.addAttribute("searchMap", searchMap);
        //分页
        int currentPage = Integer.parseInt(searchMap.get("currentPage"));
        model.addAttribute("currentPage", currentPage);

        return "search";
    }
}
